from functools import reduce
import gi

gi.require_version("Gtk", "4.0")
gi.require_version("GtkSource", "5")

from she.autocomplete import SQLCompletionProvider
from she.dialog import CustomFormDialog

from gi.repository import Gtk, GtkSource, GLib

GtkSource.init()


class MyWindow(Gtk.ApplicationWindow):
    def __init__(self, app, **kwargs):
        super().__init__(application=app, **kwargs)

        self.updating = False

        self.set_title("Sql Helper Editor")
        self.set_default_size(800, 600)

        # 主要的垂直布局
        main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.set_child(main_box)

        # 创建HeaderBar
        header_bar = Gtk.HeaderBar()
        # 添加按钮到HeaderBar
        btn_build = Gtk.Button(label="▶️ 编译")
        btn_build.set_tooltip_text("编译SQL")
        btn_build.connect("clicked", self.on_build_clicked)
        header_bar.pack_end(btn_build)

        btn_open = Gtk.Button(label="📂 打开")
        btn_open.set_tooltip_text("打开文件")
        btn_open.connect("clicked", self.on_open_file_clicked)
        header_bar.pack_start(btn_open)

        # 设置HeaderBar为窗口的标题栏
        self.set_titlebar(header_bar)

        # 创建一个水平的Paned
        paned = Gtk.Paned.new(Gtk.Orientation.HORIZONTAL)
        paned.set_wide_handle(True)  # 设置一个更宽的拖动手柄

        main_box.append(paned)

        # 创建一个CSS provider
        css_provider = Gtk.CssProvider()
        css = b"""
        textview {
            font-family: Monospace;
            font-size: 18pt;
        }
        """
        css_provider.load_from_data(css)

        # 第一个GtkSourceView
        self.sourceview1 = GtkSource.View(monospace=True)
        self.sourceview1.set_show_line_numbers(True)
        self.sourceview1.set_auto_indent(True)
        self.sourceview1.set_highlight_current_line(True)
        self.sourceview1.set_tab_width(4)
        self.sourceview1.set_insert_spaces_instead_of_tabs(True)
        self.sourceview1.set_monospace(True)
        self.sourceview1.set_hexpand(True)
        self.sourceview1.set_vexpand(True)

        # 设置每个GtkSourceView的字体大小
        text_view1 = Gtk.Widget.get_style_context(self.sourceview1)
        text_view1.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # 加载语言和主题
        manager = GtkSource.LanguageManager()
        language = manager.get_language("sql")
        self.buffer1 = GtkSource.Buffer()
        self.buffer1.set_language(language)
        self.buffer1.set_highlight_matching_brackets(True)
        self.sourceview1.set_buffer(self.buffer1)
        self.sourceview1.set_auto_indent(True)
        self.sourceview1.set_highlight_current_line(True)
        self.sourceview1.set_top_margin(10)
        self.sourceview1.set_bottom_margin(10)
        self.set_auto_completion()
        # self.buffer1.connect("changed", self.on_buffer1_changed)

        style_scheme_manager = GtkSource.StyleSchemeManager.get_default()
        style_scheme = style_scheme_manager.get_scheme("Adwaita-dark")  # 更改为你想要的主题名
        self.buffer1.set_style_scheme(style_scheme)

        # 第二个GtkSourceView
        sourceview2 = GtkSource.View()
        sourceview2.set_show_line_numbers(True)
        sourceview2.set_auto_indent(True)
        sourceview2.set_highlight_current_line(True)
        sourceview2.set_tab_width(4)
        sourceview2.set_insert_spaces_instead_of_tabs(True)
        sourceview2.set_hexpand(True)
        sourceview2.set_vexpand(True)

        # 设置每个GtkSourceView的字体大小
        text_view2 = Gtk.Widget.get_style_context(sourceview2)
        text_view2.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        # 加载语言和主题
        manager = GtkSource.LanguageManager()
        language = manager.get_language("sql")
        buffer2 = GtkSource.Buffer()
        buffer2.set_language(language)
        sourceview2.set_buffer(buffer2)

        style_scheme_manager = GtkSource.StyleSchemeManager.get_default()
        style_scheme = style_scheme_manager.get_scheme("Adwaita-dark")  # 更改为你想要的主题名
        buffer2.set_style_scheme(style_scheme)

        sw1 = Gtk.ScrolledWindow()
        sw1.set_child(self.sourceview1)

        sw2 = Gtk.ScrolledWindow()
        sw2.set_child(sourceview2)

        # 将两个ScrolledWindow添加到Paned中
        paned.set_start_child(sw1)
        paned.set_end_child(sw2)

        # 状态栏
        statusbar = Gtk.Statusbar()
        context_id = statusbar.get_context_id("Status Bar")
        statusbar.push(context_id, "This is a status bar.")
        main_box.append(statusbar)

    def on_open_file_clicked(self, widget):
        print("Open file button clicked")
        self.file_chooser = Gtk.FileChooserNative.new(
            title="选择SQL文件", parent=self, action=Gtk.FileChooserAction.OPEN
        )

        # 设置文件过滤器
        filter_text = Gtk.FileFilter()
        filter_text.set_name("SQL文件")
        filter_text.add_mime_type("application/sql")
        self.file_chooser.add_filter(filter_text)

        # 显示文件选择对话框
        self.file_chooser.show()
        self.file_chooser.set_modal(True)
        self.file_chooser.connect("response", self.on_file_chooser_response)
        self.file_chooser.show()

    def on_build_clicked(self, widget):
        dialog = CustomFormDialog(
            self, title="参数", fields=["Name", "Email", "Phone"], on_submit_clicked=self.on_submit_clicked
        )
        dialog.present()

    def on_submit_clicked(self, widget, *entries):
        results = reduce(lambda res, e: res | {e[0]: e[1].get_text()}, entries, {})
        print(results)
        self.destroy()

    def on_file_chooser_response(self, file_chooser, response):
        if response == Gtk.ResponseType.ACCEPT:
            sql_file = file_chooser.get_file().get_path()
            # 在这里处理打开的文件
            print(f"Opening file: {sql_file}")
            with open(sql_file, "r") as file:
                content = file.read()
                self.buffer1.set_text(content)

        elif response == Gtk.ResponseType.CANCEL:
            pass
        file_chooser.destroy()
        self.export_dialog = None

    def set_auto_completion(self):
        """设置自动补全"""
        # 添加补全提供者
        self.completion = self.sourceview1.get_completion()
        self.provider = SQLCompletionProvider()
        self.completion.add_provider(self.provider)

    def on_buffer1_changed(self, buffer):
        if self.buffer1 and not self.updating:
            self.updating = True
            text = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), False)
            print(">>>", text)
            self.updating = False



class MyApp(Gtk.Application):
    def __init__(self):
        super().__init__(application_id="com.zkz.bms.she")

    def do_activate(self):
        win = MyWindow(self)
        win.present()


def main():
    app = MyApp()
    app.run(None)


if __name__ == "__main__":
    main()
